<?php
//+---------------------------------------------------------------------------------------------------------------------
//| 人生是荒芜的旅行，冷暖自知，苦乐在心
//+---------------------------------------------------------------------------------------------------------------------
//| Author:Janmas <janmas@126.com>
//+---------------------------------------------------------------------------------------------------------------------
//| 
//+---------------------------------------------------------------------------------------------------------------------


namespace app\common\model;


use helper\upload\BaseUpload;
use think\Exception;
use think\File;
use think\model\concern\SoftDelete;

class FileManager extends BaseModel
{
	use SoftDelete;

	protected $autoWriteTimestamp = true;

	protected $createTime = 'createtime';

	protected $updateTime = false;

	protected $defaultSoftDelete = null;

	protected $deleteTime = 'deletetime';

	protected $name = 'files_manager';

	protected $schema = [
		'id'         => 'int',
		'name'       => 'string',
		'path'       => 'string',
		'size'       => 'int',
		'md5'        => 'string',
		'ext'        => 'string',
		'memi'       => 'string',
		'thumb'      => 'string',
		'driver'     => 'string',
		'uid'        => 'int',
		'createtime' => 'int',
		'deletetime' => 'int',
	];

	/**
	 * 新增、更新需要操作的字段
	 */
	protected $submitField = [

	];

    protected $append = [
        'file_url',
        'format_size'
    ];

    public function getFileUrlAttr($value,$data )
    {
        return set_file_domain($data['path']);
    }

    public function getFormatSizeAttr($value,$data){
        return format_file_size($data['size']);
    }

	/**
	 * @param File[] $file
	 */
	public static function upload($files=null){
		if(is_null($files)){
			return 0;
		}
		$files = is_array($files)?$files:[$files];

		$uploadClassName = 'helper\\upload\\' . ucfirst(config('driver.driver')??'local');

		/**
		 * @var BaseUpload $uploadClass
		 */
		$uploadClass = $uploadClassName::instance(config('upload'));

		self::startTrans();

		/**
		 * @var File[] $files
		 */
		foreach($files as $file){
			try{
				$model = self::where('md5',$file->md5())->findOrEmpty();
				if($model->isEmpty()){
					$model = self::create($uploadClass->upload($file));
				}
				$fileIds[] = $model->id;
			}catch (\Exception $e){
				throw $e;
			}

		}

		if(count($fileIds) == count($files)){
			self::commit();
			return count($fileIds) <= 1?array_shift($fileIds):json(',',$fileIds);
		}

		self::rollback();
		throw new Exception('文件保存失败');

	}
}